package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DBUtil {
    private static final Logger logger = Logger.getLogger(DBUtil.class.getName());
    private static final String JDBC_URL = "jdbc:mysql://localhost:3306/l_r?useSSL=false&serverTimezone=UTC";
    private static final String JDBC_USER = "root"; // 确保这是你的数据库用户名
    private static final String JDBC_PASSWORD = "xr18873947739"; // 确保这是你的数据库密码

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            logger.log(Level.SEVERE, "MySQL JDBC驱动未找到", e);
            throw new RuntimeException("MySQL JDBC驱动未找到", e);
        }
    }

    public static Connection getConnection() throws SQLException {
        Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);
        logger.info("成功连接到数据库");
        return conn;
    }

    public static void close(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                logger.log(Level.WARNING, "关闭数据库连接时出错", e);
            }
        }
    }
}